import sys
import os

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from src.server import RedisServer, app, redis_server
import argparse


def run_server(transport_type="stdio", sse_port=3334, http_port=8000):
    print(f"Starting Redis MCP Server with {transport_type} transport...")
    print(f"Redis: {redis_server.host}:{redis_server.port}/{redis_server.db}")

    try:
        if transport_type == "stdio":
            app.run(transport="stdio")
        elif transport_type == "sse":
            print(f"SSE server listening on port {sse_port}")
            app.run(transport="sse", port=sse_port)
        elif transport_type in ["http", "streamable-http"]:
            print(f"HTTP server listening on port {http_port}")
            app.run(transport="http", port=http_port)
    except KeyboardInterrupt:
        print("\nServer stopped.")


def cli():
    parser = argparse.ArgumentParser(description="Redis MCP Server")
    parser.add_argument(
        "--transport",
        default="sse",
        choices=["stdio", "sse", "http", "streamable-http"],
        help="MCP Transport type",
    )
    parser.add_argument("--host", default="localhost", help="Redis host")
    parser.add_argument("--port", default=6379, type=int, help="Redis port")
    parser.add_argument("--db", type=int, default=0, help="Redis database")
    parser.add_argument("--password", help="Redis password")
    parser.add_argument("--username", help="Redis username")
    parser.add_argument(
        "--sse-port", type=int, default=3334, help="Port for SSE transport"
    )
    parser.add_argument(
        "--http-port", type=int, default=8000, help="Port for HTTP transport"
    )
    args = parser.parse_args()

    server_instance = RedisServer(
        host=args.host,
        port=args.port,
        db=args.db,
        password=args.password,
        username=args.username,
    )

    global redis_server
    redis_server = server_instance

    from tools import get, set, scan

    get.redis_server = redis_server
    set.redis_server = redis_server
    scan.redis_server = redis_server

    run_server(args.transport, args.sse_port, args.http_port)


if __name__ == "__main__":
    cli()
